package com.mlm.mlmapp.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.CustomDialog;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.CheckedChange;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.payment)
public class PaymentActivity extends BaseActivity implements HTTPCons {
    AQuery aq;
    AjaxCallback<JSONObject> getPaymentInfoCB;
    List<RadioButton> radioGroup;

    @StringRes
    String money;
    @Pref
    Prefs_ pref;
    @Extra
    String orderid;
    @Extra
    String couponid;


    @Extra
    String stylistId;

    @Extra
    String timeId;
    @Extra
    String studioId;
    @Extra
    String comboId;
    @Extra
    String productIds;
    @Extra
    String opusId;
    @Extra
    String userCouponId;
    @Extra
    String userCouponName;
    @Extra
    String integral;
    @Extra
    String integralMoney;
    @Extra
    String displayJson;
    @ViewById
    CheckBox btn_money;
    @ViewById
    RelativeLayout dingjin;
    @ViewById
    ImageView btn_headimg;
    @ViewById
    TextView tv_dresser;
    @ViewById
    Button tv_post;
    @ViewById
    LinearLayout items;
    @ViewById
    Button btn_date;
    @ViewById
    Button btn_studio;
    @ViewById
    Button btn_coupon;
    @ViewById
    TextView tv_money;
    @ViewById
    TextView btn_next;
    @ViewById
    TextView tv_point;
    @ViewById
    TextView tv_pointmoney;
    @ViewById
    LinearLayout pros;
    @ViewById
    Button btn_username;
    @ViewById
    Button btn_total;
    @ViewById
    TextView tv_dingjin3;
    @ViewById
    CheckBox btn_point;
    @ViewById
    RadioButton btn_alipay;
    @ViewById
    RadioButton btn_wechat;
    @ViewById
    ViewStub tipstub;
    @ViewById
    Button btn_paymoney;
    @ViewById
    TextView tv_dingjin1;
    String outtradeno;
    LayoutInflater inflater;
    @ColorRes
    int red;
    @ColorRes
    int blacktext;
    @ColorRes
    int greyborder;
    @ColorRes
    int lightgreytext;
    @DrawableRes
    Drawable red_edge_btn_long;
    private int total = 0;
    private static final int PAYMENT_TYPE_ALIPAY = 0;
    private static final int PAYMENT_TYPE_WECHAT = 1;
    private static final int PAYMENT_PAYING = 2;
    private static final int PAYMENT_SUCCESS = 3;
    private int payment_type;
    public static final String ORDER_REFRESH_FLAG = "com.mlm.mlmapp.order.refresh";
    String depFund;
    int intdepFund;
    String orderMoney;
    int intordermoney;
    int realMoney;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent); // 这一句必须的，否则Intent无法获得最新的数据
        this.orderid = intent.getStringExtra("orderid");
        // api = WXAPIFactory.createWXAPI(this, "wxb4ba3c02aa476ea1");
    }

    @AfterViews
    void init() {
        // api = WXAPIFactory.createWXAPI(this, "wxb4ba3c02aa476ea1");
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }
        aq = new AQuery(this);
        getUserInfo();
        inflater = LayoutInflater.from(this);

        btn_paymoney.setText(getString(R.string.money, total));
//        tv_money.setText(getString(R.string.money, total));
//        getPaymentInfoCB = new AjaxCallback<JSONObject>() {
//
//            @Override
//            public void callback(String url, JSONObject html, AjaxStatus status) {
//                if (status.getCode() == -101) {
//                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
//                            Toast.LENGTH_SHORT);
//                    return;
//                }
//                if (status.getCode() == -103) {
//                    Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
//                            Toast.LENGTH_SHORT).show();
//                } else {
//                    if (status.getCode() != 200) {
//                        Toast.makeText(aq.getContext(),
//                                "网络异常:" + status.getCode(), Toast.LENGTH_SHORT)
//                                .show();
//                    } else {
//                        try {
//                            onSuccess(html);
//                        } catch (JSONException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        };

        try {
            JSONObject object = new JSONObject(displayJson);
            onSuccess(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @OnActivityResult(REQUEST_CODE_VALID_COUPON)
    void onResultCOMBO(int resultcode, Intent data) {
        if (resultcode == RESULT_CANCELED) {
            return;
        }
        if (data != null) {
            try {
                JSONObject obj = new JSONObject(
                        data.getStringExtra("jsonString"));
                couponid = getJsonString(obj, "id");
                getCalcAction();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    void getCalcAction() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("stylistId", stylistId));
        pairs.add(new BasicNameValuePair("timeId", timeId));
        pairs.add(new BasicNameValuePair("comboId", comboId));
        pairs.add(new BasicNameValuePair("productIds", productIds));
        pairs.add(new BasicNameValuePair("userCouponId", userCouponId));
        if (btn_point.isChecked()) {
            pairs.add(new BasicNameValuePair("integral", integralMoney));
        } else {
            pairs.add(new BasicNameValuePair("integral", ""));
        }

        CommonUtils.postRequest(get_calc, aq, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject obj, AjaxStatus status) {

                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                            Toast.LENGTH_SHORT).show();
                } else {
                    if (status.getCode() != 200) {
                        Toast.makeText(aq.getContext(),
                                "网络异常:" + status.getCode(), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        try {
                            if (obj.getBoolean("isSuccess")) {

//                                btn_total.setText(getString(R.string.money, obj
//                                        .getJSONArray("errors").getInt(0)));
                                //实付金额

                                if ((obj.getJSONArray("errors").getInt(0)) <= 50) {
                                    dingjin.setVisibility(View.GONE);
                                    tv_money.setText(getString(R.string.money, obj
                                            .getJSONArray("errors").getInt(0)));
                                    btn_paymoney.setText(getString(R.string.money, obj
                                            .getJSONArray("errors").getInt(0)));
                                } else {
                                    btn_paymoney.setText(getString(R.string.money, obj
                                            .getJSONArray("errors").getInt(0)));
                                    if (btn_money.isChecked()) {

                                        tv_money.setText("￥" + depFund);
                                        tv_dingjin3.setText(getString(R.string.pay, (obj
                                                .getJSONArray("errors").getInt(0)) - intdepFund));
                                    } else {
                                        tv_money.setText(getString(R.string.money, obj
                                                .getJSONArray("errors").getInt(0)));
                                        tv_dingjin3.setText(getString(R.string.pay, (obj
                                                .getJSONArray("errors").getInt(0)) - intdepFund));
                                    }
                                }


                            } else {
                                Toast.makeText(aq.getContext(),
                                        obj.getString("errors"),
                                        Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            //
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }

        }, pairs);
    }

    @Click
    void btn_money() {
        if (btn_money.isChecked()) {
            tv_money.setText("￥" + depFund);
        } else {
            tv_money.setText(btn_paymoney.getText());
        }
    }

    private void getUserInfo() {
        AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), "",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {

                    // MainActivity_.intent(LoginActivity.this).start();
                    // userName iconPhotoUrl mobile balance integral
                    // collecNum couponNum

                    btn_username.setText(CommonUtils.getJsonString(html,
                            "userName"));

                }
            }
        };
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        // pairs.add(new BasicNameValuePair("mobile", "18245189375"));

        CommonUtils.postRequest(get_user_info_action, aq, cb, pairs);
    }

    void getCouponCountAction() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("stylistId", stylistId));
        pairs.add(new BasicNameValuePair("timeId", timeId));
        pairs.add(new BasicNameValuePair("comboId", comboId));
        pairs.add(new BasicNameValuePair("productIds", productIds));
        pairs.add(new BasicNameValuePair("userCouponId", userCouponId));

        CommonUtils.postRequest4Array(get_user_coupon, aq,
                new AjaxCallback<JSONArray>() {

                    @Override
                    public void callback(String url, JSONArray array,
                                         AjaxStatus status) {

                        if (userCouponName != null) {
                            btn_coupon.setText(userCouponName);
                        } else {
                            if (array != null) {
                                if (couponcount == 0) {
                                    btn_coupon.setText(getString(
                                            R.string.coupon_valid, array.length()));
                                    if (array.length() > 0) {
//                                    btn_coupon.setTextColor(red);
                                        btn_coupon.setClickable(true);
                                    } else {
//                                    btn_coupon.setTextColor(lightgreytext);
                                        btn_coupon.setClickable(false);
                                    }
                                } else {
                                    btn_coupon.setText(getString(
                                            R.string.coupon_valid, 0));
//                                btn_coupon.setTextColor(lightgreytext);
                                    btn_coupon.setClickable(false);
                                }

                            }
                        }


                    }

                }, pairs);
    }

    private int couponcount;


    void onSuccess(JSONObject obj) throws JSONException {


        aq.id(btn_headimg).image(getJsonString(obj, "iconPhotoUrl"), true,
                true, 200, 0, null, Constants.FADE_IN);
        //couponcount = getJsonInt(obj, "isCoupon");
        btn_coupon.setText(getString(R.string.coupon_valid, 0));
        getCouponCountAction();
        // if (couponcount <= 0) {
        // btn_coupon.setTextColor(red);
        // btn_coupon.setClickable(true);
        // } else {
        // btn_coupon.setTextColor(lightgreytext);
        // btn_coupon.setClickable(false);
        //
        // }
        tv_pointmoney.setText(getString(R.string.money,
                getJsonInt(obj, "integralMoney")));
        tv_point.setText(getString(R.string.point, getJsonInt(obj, "integral")));
        if (getJsonInt(obj, "integral") == 0) {
//            btn_point.setEnabled(false);
            btn_point.setVisibility(View.INVISIBLE);
            tv_pointmoney.setVisibility(View.INVISIBLE);
            tv_point.setText("无可用积分");
        }
//		btn_username.setText(getJsonString(obj, "userName"));
        btn_date.setText(getJsonString(obj, "appointTimes"));
        tv_dresser.setText(getJsonString(obj, "name"));
        tv_post.setText(getJsonString(obj, "leveName"));
        btn_total.setText(getString(R.string.money,
                getJsonInt(obj, "orderMoney")));
        orderMoney = getJsonString(obj, "orderMoney");

        intordermoney = Integer.parseInt(orderMoney);
        //如果订单需支付金额 > 50 可选择仅支付定金
        if (intordermoney > 50) {
            dingjin.setVisibility(View.VISIBLE);
        } else {
            dingjin.setVisibility(View.GONE);
        }
        btn_paymoney.setText(getString(R.string.money,
                getJsonInt(obj, "orderMoney")));
        //服务完成扣除金额
        tv_dingjin1.setText(getString(R.string.money, getJsonInt(obj, "depFund")));
        depFund = getJsonString(obj, "depFund");
        tv_dingjin3.setText(getString(R.string.money, intordermoney - getJsonInt(obj, "depFund")));
        intdepFund = getJsonInt(obj, "depFund");
//        realMoney = getJsonInt(obj, "realMoney");
        tv_money.setText(getString(R.string.money,
                getJsonInt(obj, "orderMoney")));
        JSONArray array = getJsonArray(obj, "bookProducts");
        items.removeAllViews();
        for (int i = 0; i < array.length(); i++) {
            final JSONObject temp = array.getJSONObject(i);
            if (!temp.isNull("productName")) {
                View view = inflater.inflate(R.layout.payment_group_item, null);
                ((TextView) view.findViewById(R.id.row_group_item))
                        .setText(getJsonString(temp, "productName"));
                ((TextView) view.findViewById(R.id.row_price))
                        .setText(
                                getJsonString(temp, "price"));
                items.addView(view);
            }
        }
        JSONObject studio = getJsonObject(obj, "studio");
        btn_studio.setText(getJsonString(studio, "names"));
    }

    private void submitAction() {
        AjaxCallback<JSONObject> submitCallback = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {

                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {

                            // MainActivity_.intent(LoginActivity.this).start();

                            orderid = getJsonArray(html, "errors").getString(0);
                            if (orderid.equals("-1")) {

                                //成功
                                showAlertDialog();
                                return;
                            }
                            PaymentOrderActivity_.intent(PaymentActivity.this)
                                    .extra("orderid", orderid).startForResult(REQUEST_CODE_PAYMENT);
                            PaymentActivity.this.finish();
                            //// TODO: 2016/3/10
//							BookActivity.this.finish();
                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
        String mobile = pref.loginID().get();
        if (couponid == null) {
            couponid = "";
        }

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", mobile));
        pairs.add(new BasicNameValuePair("stylistId", stylistId));
        pairs.add(new BasicNameValuePair("timeId", timeId));
        pairs.add(new BasicNameValuePair("studioId", studioId));
        pairs.add(new BasicNameValuePair("comboId", comboId));
        pairs.add(new BasicNameValuePair("productIds", productIds));
        pairs.add(new BasicNameValuePair("opusId", opusId));
        pairs.add(new BasicNameValuePair("userCouponId", userCouponId));
        if (btn_point.isChecked()) {
            pairs.add(new BasicNameValuePair("integral", integralMoney));
        } else {
            pairs.add(new BasicNameValuePair("integral", ""));
        }
        if (View.VISIBLE == dingjin.getVisibility()) {
            if (btn_money.isChecked()) {
                pairs.add(new BasicNameValuePair("isDepFund", "2"));
            } else {
                pairs.add(new BasicNameValuePair("isDepFund", "1"));
            }
        } else {
            pairs.add(new BasicNameValuePair("isDepFund", "1"));
        }
        CommonUtils.postRequest(submit_order_action, aq, submitCallback, pairs);


    }

    @Click
    void btn_next() {
        submitAction();

    }

    @CheckedChange
    void btn_point() {

        if (btn_point.isChecked()) {
            getCalcAction();
        } else {
            if (btn_money.isChecked()) {
                tv_money.setText("￥" + depFund);
            } else {
                tv_money.setText("￥" + orderMoney);
            }
            if (Integer.valueOf(orderMoney) <= 50) {
                dingjin.setVisibility(View.GONE);
            } else {
                dingjin.setVisibility(View.VISIBLE);
            }

            tv_dingjin3.setText("￥" + (Integer.parseInt(orderMoney) - Integer.parseInt(depFund)));
            btn_paymoney.setText("￥" + orderMoney);


        }
    }


    @Click
    void btn_coupon() {
        if (couponid != null && !"".equals(couponid)) {
            CouponListActivity_.intent(this).extra("couponid", couponid)
                    .extra("id", orderid).startForResult(REQUEST_CODE_VALID_COUPON);
        }
    }

    public void showAlertDialog() {
        CommonUtils.sendBroadCast(this, CollectionsActivity.COLLECTION_REFRESH, "refreshflag", "0");
        CustomDialog.Builder builder = new CustomDialog.Builder(this);

        builder.setPositiveButton("返回首页", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                MainActivity_.intent(PaymentActivity.this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
                dialog.dismiss();
                PaymentActivity.this.finish();

                //设置你的操作事项
            }
        });

        builder.setNegativeButton("查看订单",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        OrdersActivity_.intent(PaymentActivity.this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).extra("flag", OrdersActivity.TYPE_BOOKED).start();
//                        OrdersActivity_.intent(PaymentActivity.this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
//                        //// TODO: 2016/3/10
                        Intent intent = new Intent();
                        intent.setAction(ORDER_REFRESH_FLAG);
                        intent.putExtra("refreshflag", "0");
                        getBaseContext().sendOrderedBroadcast(intent, null);
                        dialog.dismiss();
                        PaymentActivity.this.finish();
                    }
                });

        builder.create().show();

    }

    @Click
    void btn_back() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        Intent data = new Intent();
        setResult(RESULT_CANCELED, data);
        this.finish();
    }

}
